package top.likeqc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.Grade;
import top.likeqc.entity.Student;
import top.likeqc.service.IGradeService;
import top.likeqc.service.IStudentService;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 年级表 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-10
 */
@RestController
@RequestMapping("/grade")
public class GradeController extends BaseController {
    @Autowired
    IGradeService gradeService;

    @Autowired
    IStudentService studentService;

    /**
     * 查询 年级表
     *
     * @param keyStr
     * @return
     */
    @GetMapping("")
    public Result list(String keyStr) {
        Page<Grade> page = gradeService.page(getPage(),
            new QueryWrapper<Grade>().like(StringUtils.isNoneBlank(keyStr), "name",
                keyStr));

        return Result.success(page);
    }

    /**
     * 新增、修改 年级
     * @param grade
     * @return
     */
    @PostMapping("")
    public Result edit(@RequestBody Grade grade) {
        boolean b = gradeService.saveOrUpdate(grade);
        if (b) {
            return Result.success(grade);
        } else {
            return Result.fail("新增、修改年级，操作失败");
        }
    }

    /**
     * 删除 年级
     * @param gradeIds
     * @return
     */
    @DeleteMapping("")
    public Result delete(@RequestBody List<Integer> gradeIds) {
        Student student = studentService.getOne(new QueryWrapper<Student>().in("grade_id", gradeIds));
        if (student != null) {
            return Result.fail("该年级有学生，不嫩删除");
        }
        boolean b = gradeService.removeByIds(gradeIds);
        if (b) {
            return Result.success();
        } else {
            return Result.fail("新增、修改年级，操作失败");
        }
    }
}
